﻿using Microsoft.Extensions.Configuration;
using System;
using System.Net.Http;
using SSharing.Frameworks.NetCore.Common.Extends;
using Polly;
using Microsoft.Extensions.Logging;
using FeiShu.IService.User;
using FeiShu.Adapter;
using FeiShu.Entity.Adapter.FeiShuWork;
using FeiShu.IService.Common;

namespace FeiShu.Service.User
{
    public class UserService : IUserService
    {
        private readonly FeiShuWorkAdapter _feiShuWorkAdapter;
        private readonly ILogger<UserService> _logger;
        private readonly ICommonService _commonService;

        public UserService(IHttpClientFactory clientFactory, ICommonService commonService, ILogger<UserService> logger)
        {
            _commonService = commonService;
            _feiShuWorkAdapter = new FeiShuWorkAdapter(clientFactory, logger);
            _logger = logger;
        }

        /// <summary>
        /// 根据code获取成员信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public UserAccessTokenResponse GetUserInfo(string code)
        {
            var aa = _commonService.GetAccessToken();
            var polly = Policy
                    .HandleResult<UserAccessTokenResponse>(rs => rs != null && rs.code == 4001)
                    .Retry(3, (ex, count) =>
                    {
                        //刷新access token
                        _commonService.RefreshAccessToken();
                        _logger.LogInformation(string.Format("获取成员信息时access token过期，第{0}次刷新access token", count));
                    });
            return polly.Execute(() =>
            {
                var accessToken = _commonService.GetAccessToken().tenant_access_token;
                return _feiShuWorkAdapter.GetUserAccessToken(accessToken, code);
            });
        }
    }
}
